Page({
  data: {
    // 用户登录状态
    isLogin: false,
    userPhone: '',
    userNickname: '',

    // 模拟账户信息
    account: {
      totalAssets: 0,      // 总资产
      availableCash: 0,    // 可用资金
      frozenCash: 0,       // 冻结资金
      marketValue: 0,      // 持仓市值
      totalProfit: 0,      // 总盈亏
      profitRate: 0        // 盈亏比例
    },

    // 持仓股票
    positions: [],

    // 交易记录
    orders: [],



    // 当前选中的标签
    currentTab: 'account',

    // 加载状态
    loading: true,

    // 股票搜索
    searchKeyword: '',
    searchResults: [],
    showSearchResults: false,
    showSearchDialog: false,

    // 交易弹窗
    showTradeModal: false,
    tradeType: 'buy', // buy/sell
    selectedStock: null,
    tradeShares: '',
    tradePrice: '',

    // 初始化状态
    isInitialized: false,

    // 搜索定时器
    searchTimer: null,

    // 云函数状态
    cloudFunctionReady: false
  },

  onLoad: function (options) {
    // 检查登录状态
    this.checkLoginStatus();

    // 设置页面标题
    wx.setNavigationBarTitle({
      title: '模拟炒股'
    });

    // 初始化云数据库
    this.initCloudDatabase();
  },

  onShow: function () {
    // 每次显示页面时刷新登录状态和数据
    this.checkLoginStatus();

    if (this.data.isLogin) {
      this.loadAllData();
    }
  },

  // 检查登录状态
  checkLoginStatus: function () {
    const app = getApp();
    const isLogin = app.globalData.isLogin || false;
    const userPhone = app.globalData.userPhone || '';
    const userNickname = app.globalData.userNickname || userPhone || '投资者';

    this.setData({
      isLogin: isLogin,
      userPhone: userPhone,
      userNickname: userNickname,
      loading: false // 确保未登录时不显示加载状态
    });

    if (isLogin && !this.data.isInitialized) {
      this.setData({
        loading: true
      });
      this.initializeAccount();
    }
  },

  // 初始化云数据库
  initCloudDatabase: function () {
    if (!wx.cloud) {
      console.error('请在 app.js 中初始化云开发');
      this.setData({
        loading: false
      });
      return;
    }

    try {
      this.db = wx.cloud.database();
      console.log('云数据库初始化成功');
    } catch (error) {
      console.error('云数据库初始化失败:', error);
      this.setData({
        loading: false
      });
    }
  },

  // 初始化账户
  initializeAccount: function () {
    const that = this;

    // 检查数据库是否已初始化
    if (!this.db) {
      console.error('数据库未初始化');
      this.setData({
        loading: false
      });
      return;
    }

    // 先尝试使用云函数
    wx.cloud.callFunction({
      name: 'simulationAccount',
      data: {
        action: 'initialize'
      },
      success(res) {
        console.log('账户初始化结果:', res.result);
        if (res.result.success) {
          that.setData({
            isInitialized: true,
            account: res.result.account,
            cloudFunctionReady: true
          });
          that.loadAllData();
        } else {
          console.error('账户初始化失败:', res.result.message);
          that.setData({
            loading: false
          });
        }
      },
      fail(err) {
        console.error('调用账户初始化云函数失败:', err);
        // 云函数调用失败，使用本地数据库操作作为备选方案
        that.initializeAccountLocal();
      }
    });
  },

  // 本地数据库初始化账户（备选方案）
  initializeAccountLocal: function () {
    const that = this;

    // 检查是否已有账户
    this.db.collection('simulation_accounts').where({
      _openid: wx.cloud.database().command.exists(true)
    }).get({
      success(res) {
        if (res.data.length === 0) {
          // 创建新账户
          that.createNewAccountLocal();
        } else {
          // 加载现有账户数据
          that.setData({
            isInitialized: true,
            account: res.data[0]
          });
          that.loadAllData();
        }
      },
      fail(err) {
        console.error('检查账户失败:', err);
        // 如果数据库集合不存在，创建默认账户
        that.createDefaultAccount();
      }
    });
  },

  // 本地创建新账户
  createNewAccountLocal: function () {
    const that = this;
    const initialCash = 1000000; // 初始资金100万

    this.db.collection('simulation_accounts').add({
      data: {
        totalAssets: initialCash,
        availableCash: initialCash,
        frozenCash: 0,
        marketValue: 0,
        totalProfit: 0,
        profitRate: 0,
        createTime: new Date(),
        updateTime: new Date()
      },
      success(res) {
        console.log('本地账户创建成功:', res);
        that.setData({
          isInitialized: true,
          account: {
            totalAssets: initialCash,
            availableCash: initialCash,
            frozenCash: 0,
            marketValue: 0,
            totalProfit: 0,
            profitRate: 0
          }
        });
        that.loadAllData();

        wx.showToast({
          title: '账户创建成功！',
          icon: 'success'
        });
      },
      fail(err) {
        console.error('本地账户创建失败:', err);
        that.createDefaultAccount();
      }
    });
  },

  // 创建默认账户（最后备选方案）
  createDefaultAccount: function () {
    const initialCash = 1000000;

    this.setData({
      isInitialized: true,
      account: {
        totalAssets: initialCash,
        availableCash: initialCash,
        frozenCash: 0,
        marketValue: 0,
        totalProfit: 0,
        profitRate: 0
      },
      loading: false
    });

    wx.showToast({
      title: '使用演示账户',
      icon: 'none',
      duration: 2000
    });

    console.log('使用默认演示账户');
  },



  // 加载所有数据
  loadAllData: function () {
    if (!this.data.isLogin) {
      this.setData({
        loading: false
      });
      return;
    }

    this.setData({
      loading: true
    });

    Promise.all([
      this.loadAccountData(),
      this.loadPositions(),
      this.loadOrders()
    ]).then(() => {
      this.setData({
        loading: false
      });
    }).catch(err => {
      console.error('加载数据失败:', err);
      this.setData({
        loading: false
      });
    });
  },

  // 加载账户数据
  loadAccountData: function () {
    return new Promise((resolve, reject) => {
      wx.cloud.callFunction({
        name: 'simulationAccount',
        data: { action: 'getAccount' },
        success: (res) => {
          if (res.result.success) {
            this.setData({
              account: res.result.account
            });
          }
          resolve(res);
        },
        fail: reject
      });
    });
  },

  // 加载持仓数据
  loadPositions: function () {
    return new Promise((resolve, reject) => {
      wx.cloud.callFunction({
        name: 'simulationTrade',
        data: { action: 'getPositions' },
        success: (res) => {
          console.log('持仓数据加载结果:', res.result);
          if (res.result.success) {
            this.setData({
              positions: res.result.positions || []
            });
            // 更新持仓实时价格
            if (res.result.positions && res.result.positions.length > 0) {
              this.updatePositionPrices();
            }
          } else {
            console.error('加载持仓失败:', res.result.message);
            this.setData({
              positions: []
            });
          }
          resolve(res);
        },
        fail: (err) => {
          console.error('调用持仓云函数失败:', err);
          // 使用本地数据作为备选
          this.setData({
            positions: this.data.positions || []
          });
          reject(err);
        }
      });
    });
  },

  // 加载订单数据
  loadOrders: function () {
    return new Promise((resolve, reject) => {
      wx.cloud.callFunction({
        name: 'simulationTrade',
        data: { action: 'getOrders' },
        success: (res) => {
          console.log('订单数据加载结果:', res.result);
          if (res.result.success) {
            this.setData({
              orders: res.result.orders || []
            });
          } else {
            console.error('加载订单失败:', res.result.message);
            this.setData({
              orders: []
            });
          }
          resolve(res);
        },
        fail: (err) => {
          console.error('调用订单云函数失败:', err);
          // 使用本地数据作为备选
          this.setData({
            orders: this.data.orders || []
          });
          reject(err);
        }
      });
    });
  },



  // 更新持仓实时价格
  updatePositionPrices: function () {
    const positions = this.data.positions;
    if (positions.length === 0) return;

    const stockCodes = positions.map(pos => pos.stockCode).join(',');

    wx.request({
      url: `https://hq.sinajs.cn/list=${stockCodes}`,
      success: (res) => {
        this.parsePositionPrices(res.data);
      },
      fail: (err) => {
        console.error('获取股票价格失败:', err);
      }
    });
  },

  // 解析持仓价格数据
  parsePositionPrices: function (data) {
    try {
      const lines = data.split('\n');
      const updatedPositions = [...this.data.positions];
      let totalMarketValue = 0;
      let totalProfit = 0;

      lines.forEach((line, index) => {
        if (!line.trim() || index >= updatedPositions.length) return;

        const regex = /=\"(.*)\"\;/;
        const matches = line.match(regex);

        if (matches && matches[1]) {
          const elements = matches[1].split(',');
          const currentPrice = parseFloat(elements[3]);

          if (currentPrice > 0) {
            const position = updatedPositions[index];
            const marketValue = currentPrice * position.shares;
            const profit = marketValue - position.totalCost;
            const profitRate = (profit / position.totalCost) * 100;

            position.currentPrice = currentPrice;
            position.marketValue = marketValue;
            position.profit = profit;
            position.profitRate = profitRate;

            totalMarketValue += marketValue;
            totalProfit += profit;
          }
        }
      });

      // 更新账户信息
      const account = { ...this.data.account };
      account.marketValue = totalMarketValue;
      account.totalAssets = account.availableCash + totalMarketValue;
      account.totalProfit = totalProfit;
      account.profitRate = totalProfit > 0 ? (totalProfit / (account.totalAssets - totalProfit)) * 100 : 0;

      this.setData({
        positions: updatedPositions,
        account: account
      });

      // 更新数据库中的账户信息
      this.updateAccountInDB(account);

    } catch (error) {
      console.error('解析价格数据失败:', error);
    }
  },

  // 更新数据库中的账户信息
  updateAccountInDB: function (account) {
    wx.cloud.callFunction({
      name: 'simulationAccount',
      data: {
        action: 'updateAccount',
        totalAssets: account.totalAssets,
        marketValue: account.marketValue,
        totalProfit: account.totalProfit,
        profitRate: account.profitRate
      },
      success(res) {
        console.log('账户信息更新成功');
      },
      fail(err) {
        console.error('账户信息更新失败:', err);
      }
    });
  },

  // 切换标签
  switchTab: function (e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      currentTab: tab
    });
  },

  // 显示搜索对话框
  showSearchDialog: function () {
    if (!this.data.isLogin) {
      wx.navigateTo({
        url: '/pages/login/index'
      });
      return;
    }

    this.setData({
      showSearchDialog: true,
      searchKeyword: '',
      searchResults: [],
      showSearchResults: false
    });
  },

  // 隐藏搜索对话框
  hideSearchDialog: function () {
    this.setData({
      showSearchDialog: false,
      searchKeyword: '',
      searchResults: [],
      showSearchResults: false
    });
  },

  // 一键卖出
  quickSell: function (e) {
    const stock = e.currentTarget.dataset.stock;
    const that = this;

    wx.showModal({
      title: '确认卖出',
      content: `确定要卖出全部 ${stock.stockName}(${stock.stockCode}) 吗？\n持仓：${stock.shares}股\n当前价：¥${stock.currentPrice}`,
      success(res) {
        if (res.confirm) {
          // 执行卖出操作
          that.executeSell(stock);
        }
      }
    });
  },

  // 执行卖出操作
  executeSell: function (stock) {
    const that = this;

    wx.showLoading({
      title: '卖出中...'
    });

    // 使用云函数卖出
    wx.cloud.callFunction({
      name: 'simulationTrade',
      data: {
        action: 'sell',
        stockCode: stock.stockCode,
        shares: stock.shares, // 全部卖出
        price: stock.currentPrice || stock.avgPrice // 使用当前价或成本价
      },
      success(res) {
        wx.hideLoading();
        console.log('卖出结果:', res.result);

        if (res.result.success) {
          wx.showToast({
            title: '卖出成功',
            icon: 'success'
          });

          // 延迟刷新数据
          setTimeout(() => {
            that.loadAllData();
          }, 500);
        } else {
          wx.showToast({
            title: res.result.message || '卖出失败',
            icon: 'none'
          });
        }
      },
      fail(err) {
        wx.hideLoading();
        console.error('调用卖出云函数失败:', err);

        // 使用本地卖出逻辑作为备选
        that.executeSellLocal(stock.stockCode, stock.stockName, stock.shares, stock.currentPrice || stock.avgPrice, stock.shares * (stock.currentPrice || stock.avgPrice));
      }
    });
  },

  // 开始演示模式
  startDemo: function () {
    const that = this;

    // 模拟搜索平安银行
    wx.showToast({
      title: '演示：搜索平安银行',
      icon: 'none',
      duration: 2000
    });

    setTimeout(() => {
      that.setData({
        showSearchDialog: true,
        searchKeyword: '平安银行',
        searchResults: [
          {
            Code: '000001',
            Name: '平安银行',
            SecurityTypeName: '深A'
          }
        ],
        showSearchResults: true
      });

      wx.showToast({
        title: '点击搜索结果体验交易',
        icon: 'none',
        duration: 3000
      });
    }, 2000);
  },

  // 检查云函数状态
  checkCloudFunction: function () {
    const that = this;

    wx.showLoading({
      title: '检测中...'
    });

    wx.cloud.callFunction({
      name: 'simulationAccount',
      data: {
        action: 'getAccount'
      },
      success(res) {
        wx.hideLoading();
        that.setData({
          cloudFunctionReady: true
        });

        wx.showToast({
          title: '云函数正常',
          icon: 'success'
        });

        // 重新初始化
        that.initializeAccount();
      },
      fail(err) {
        wx.hideLoading();
        console.error('云函数检测失败:', err);

        wx.showModal({
          title: '云函数未部署',
          content: '请在微信开发者工具中部署以下云函数：\n1. simulationAccount\n2. simulationTrade\n3. simulationData\n\n当前将使用本地演示模式',
          showCancel: false,
          confirmText: '知道了'
        });
      }
    });
  },

  // 显示交易弹窗
  showTradeDialog: function (e) {
    if (!this.data.isLogin) {
      wx.navigateTo({
        url: '/pages/login/index'
      });
      return;
    }

    const type = e.currentTarget.dataset.type || 'buy';
    const stock = e.currentTarget.dataset.stock || null;

    this.setData({
      showTradeModal: true,
      tradeType: type,
      selectedStock: stock,
      tradeShares: '',
      tradePrice: stock ? stock.currentPrice.toFixed(2) : ''
    });
  },

  // 隐藏交易弹窗
  hideTradeDialog: function () {
    this.setData({
      showTradeModal: false,
      selectedStock: null,
      tradeShares: '',
      tradePrice: ''
    });
  },

  // 输入交易数量
  onSharesInput: function (e) {
    this.setData({
      tradeShares: e.detail.value
    });
  },

  // 输入交易价格
  onPriceInput: function (e) {
    this.setData({
      tradePrice: e.detail.value
    });
  },

  // 确认交易
  confirmTrade: function () {
    const { tradeType, selectedStock, tradeShares, tradePrice } = this.data;

    if (!selectedStock) {
      wx.showToast({
        title: '请选择股票',
        icon: 'none'
      });
      return;
    }

    if (!tradeShares || parseInt(tradeShares) <= 0) {
      wx.showToast({
        title: '请输入正确的数量',
        icon: 'none'
      });
      return;
    }

    if (!tradePrice || parseFloat(tradePrice) <= 0) {
      wx.showToast({
        title: '请输入正确的价格',
        icon: 'none'
      });
      return;
    }

    if (tradeType === 'buy') {
      this.executeBuyOrder();
    } else {
      this.executeSellOrder();
    }
  },

  // 执行买入订单
  executeBuyOrder: function () {
    const { selectedStock, tradeShares, tradePrice, account } = this.data;
    const shares = parseInt(tradeShares);
    const price = parseFloat(tradePrice);
    const amount = shares * price;

    // 检查资金是否足够
    if (amount > account.availableCash) {
      wx.showToast({
        title: '资金不足',
        icon: 'none'
      });
      return;
    }

    // 创建订单
    this.createOrder('buy', selectedStock.code, selectedStock.name, shares, price, amount);
  },

  // 执行卖出订单
  executeSellOrder: function () {
    const { selectedStock, tradeShares, tradePrice } = this.data;
    const shares = parseInt(tradeShares);
    const price = parseFloat(tradePrice);
    const amount = shares * price;

    // 检查持仓是否足够
    if (shares > selectedStock.availableShares) {
      wx.showToast({
        title: '持仓不足',
        icon: 'none'
      });
      return;
    }

    // 创建订单
    this.createOrder('sell', selectedStock.stockCode, selectedStock.stockName, shares, price, amount);
  },

  // 创建订单
  createOrder: function (orderType, stockCode, stockName, shares, price, amount) {
    const that = this;

    // 先尝试使用云函数
    wx.cloud.callFunction({
      name: 'simulationTrade',
      data: {
        action: orderType,
        stockCode: stockCode,
        stockName: stockName,
        shares: shares,
        price: price
      },
      success(res) {
        console.log('交易结果:', res.result);
        console.log('交易参数:', {
          action: orderType,
          stockCode: stockCode,
          stockName: stockName,
          shares: shares,
          price: price
        });

        if (res.result.success) {
          that.hideTradeDialog();

          // 延迟刷新数据，确保云函数操作完成
          setTimeout(() => {
            that.loadAllData();
          }, 500);

          wx.showToast({
            title: res.result.message,
            icon: 'success',
            duration: 2000
          });
        } else {
          console.error('交易失败详情:', res.result);
          wx.showToast({
            title: res.result.message || '交易失败',
            icon: 'none'
          });
        }
      },
      fail(err) {
        console.error('调用交易云函数失败:', err);
        // 云函数失败，使用本地交易逻辑
        that.createOrderLocal(orderType, stockCode, stockName, shares, price, amount);
      }
    });
  },

  // 本地交易逻辑（备选方案）
  createOrderLocal: function (orderType, stockCode, stockName, shares, price, amount) {
    const that = this;

    if (orderType === 'buy') {
      // 检查资金是否足够
      if (amount > this.data.account.availableCash) {
        wx.showToast({
          title: '资金不足',
          icon: 'none'
        });
        return;
      }

      // 执行买入
      this.executeBuyLocal(stockCode, stockName, shares, price, amount);
    } else {
      // 执行卖出
      this.executeSellLocal(stockCode, stockName, shares, price, amount);
    }
  },

  // 本地买入逻辑
  executeBuyLocal: function (stockCode, stockName, shares, price, amount) {
    const that = this;

    // 更新账户资金
    const newAccount = { ...this.data.account };
    newAccount.availableCash -= amount;
    newAccount.totalAssets = newAccount.availableCash + newAccount.marketValue;

    // 更新持仓
    const positions = [...this.data.positions];
    const existingIndex = positions.findIndex(p => p.stockCode === stockCode);

    if (existingIndex >= 0) {
      // 更新现有持仓
      const position = positions[existingIndex];
      const newShares = position.shares + shares;
      const newTotalCost = position.totalCost + amount;

      positions[existingIndex] = {
        ...position,
        shares: newShares,
        availableShares: newShares,
        avgPrice: newTotalCost / newShares,
        totalCost: newTotalCost,
        marketValue: newShares * price,
        updateTime: new Date()
      };
    } else {
      // 创建新持仓
      positions.push({
        stockCode: stockCode,
        stockName: stockName,
        shares: shares,
        availableShares: shares,
        avgPrice: price,
        totalCost: amount,
        currentPrice: price,
        marketValue: amount,
        profit: 0,
        profitRate: 0,
        createTime: new Date(),
        updateTime: new Date()
      });
    }

    // 添加交易记录
    const orders = [...this.data.orders];
    orders.unshift({
      orderType: 'buy',
      stockCode: stockCode,
      stockName: stockName,
      shares: shares,
      price: price,
      amount: amount,
      status: 'filled',
      createTime: new Date().toLocaleString(),
      fillTime: new Date().toLocaleString()
    });

    // 更新页面数据
    this.setData({
      account: newAccount,
      positions: positions,
      orders: orders
    });

    this.hideTradeDialog();

    wx.showToast({
      title: '买入成功',
      icon: 'success'
    });
  },

  // 本地卖出逻辑
  executeSellLocal: function (stockCode, stockName, shares, price, amount) {
    const that = this;

    // 检查持仓
    const positions = [...this.data.positions];
    const positionIndex = positions.findIndex(p => p.stockCode === stockCode);

    if (positionIndex < 0) {
      wx.showToast({
        title: '无持仓',
        icon: 'none'
      });
      return;
    }

    const position = positions[positionIndex];
    if (position.availableShares < shares) {
      wx.showToast({
        title: '持仓不足',
        icon: 'none'
      });
      return;
    }

    // 更新账户资金
    const newAccount = { ...this.data.account };
    newAccount.availableCash += amount;

    // 更新持仓
    const newShares = position.shares - shares;
    if (newShares <= 0) {
      // 清仓
      positions.splice(positionIndex, 1);
    } else {
      // 减少持仓
      positions[positionIndex] = {
        ...position,
        shares: newShares,
        availableShares: newShares,
        totalCost: position.avgPrice * newShares,
        marketValue: newShares * price,
        updateTime: new Date()
      };
    }

    // 重新计算总资产
    newAccount.marketValue = positions.reduce((total, pos) => total + pos.marketValue, 0);
    newAccount.totalAssets = newAccount.availableCash + newAccount.marketValue;

    // 添加交易记录
    const orders = [...this.data.orders];
    orders.unshift({
      orderType: 'sell',
      stockCode: stockCode,
      stockName: stockName,
      shares: shares,
      price: price,
      amount: amount,
      status: 'filled',
      createTime: new Date().toLocaleString(),
      fillTime: new Date().toLocaleString()
    });

    // 更新页面数据
    this.setData({
      account: newAccount,
      positions: positions,
      orders: orders
    });

    this.hideTradeDialog();

    wx.showToast({
      title: '卖出成功',
      icon: 'success'
    });
  },



  // 股票搜索
  onSearchInput: function (e) {
    const keyword = e.detail.value.trim();
    this.setData({
      searchKeyword: keyword
    });

    if (!keyword) {
      this.setData({
        showSearchResults: false,
        searchResults: []
      });
      return;
    }

    // 防抖搜索
    clearTimeout(this.searchTimer);
    this.searchTimer = setTimeout(() => {
      this.searchStocks(keyword);
    }, 500);
  },

  // 执行股票搜索
  searchStocks: function (keyword) {
    const that = this;

    wx.request({
      url: 'https://searchapi.eastmoney.com/api/suggest/get',
      data: {
        input: keyword,
        type: 14,
        token: 'D43BF722C8E33BDC906FB84D85E326E8',
        count: 10
      },
      success(res) {
        if (res.data && res.data.QuotationCodeTable && res.data.QuotationCodeTable.Data) {
          const results = res.data.QuotationCodeTable.Data.filter(item => {
            return item.Classify === 'AStock' && (item.SecurityTypeName === '沪A' || item.SecurityTypeName === '深A');
          });

          that.setData({
            searchResults: results,
            showSearchResults: true
          });
        }
      },
      fail(err) {
        console.error('股票搜索失败:', err);
      }
    });
  },

  // 选择搜索结果进行交易
  selectStockForTrade: function (e) {
    const stock = e.currentTarget.dataset.stock;

    let stockCode = stock.Code;
    if (stock.SecurityTypeName === '沪A') {
      stockCode = 'sh' + stock.Code;
    } else if (stock.SecurityTypeName === '深A') {
      stockCode = 'sz' + stock.Code;
    }

    // 获取股票当前价格
    this.getStockPrice(stockCode, stock.Name);

    this.setData({
      searchKeyword: '',
      searchResults: [],
      showSearchResults: false
    });
  },

  // 获取股票价格
  getStockPrice: function (stockCode, stockName) {
    const that = this;

    wx.request({
      url: `https://hq.sinajs.cn/list=${stockCode}`,
      success(res) {
        try {
          const regex = /=\"(.*)\"\;/;
          const matches = res.data.match(regex);

          if (matches && matches[1]) {
            const elements = matches[1].split(',');
            const currentPrice = parseFloat(elements[3]);

            const stockInfo = {
              code: stockCode,
              name: stockName,
              currentPrice: currentPrice
            };

            that.setData({
              showTradeModal: true,
              tradeType: 'buy',
              selectedStock: stockInfo,
              tradeShares: '',
              tradePrice: currentPrice.toFixed(2)
            });
          }
        } catch (error) {
          console.error('解析股票价格失败:', error);
          wx.showToast({
            title: '获取股票价格失败',
            icon: 'none'
          });
        }
      },
      fail(err) {
        console.error('获取股票价格失败:', err);
        wx.showToast({
          title: '获取股票价格失败',
          icon: 'none'
        });
      }
    });
  },

  // 添加自选股
  addToWatchlist: function (e) {
    if (!this.data.isLogin) {
      wx.navigateTo({
        url: '/pages/login/index'
      });
      return;
    }

    const stock = e.currentTarget.dataset.stock;
    const that = this;

    wx.cloud.callFunction({
      name: 'simulationData',
      data: {
        action: 'addToWatchlist',
        stockCode: stock.code,
        stockName: stock.name
      },
      success(res) {
        if (res.result.success) {
          wx.showToast({
            title: res.result.message,
            icon: 'success'
          });
          that.loadWatchlist();
        } else {
          wx.showToast({
            title: res.result.message || '添加失败',
            icon: 'none'
          });
        }
      },
      fail(err) {
        console.error('添加自选股失败:', err);
        wx.showToast({
          title: '添加失败',
          icon: 'none'
        });
      }
    });
  },

  // 查看股票详情
  goToStockDetail: function (e) {
    const stock = e.currentTarget.dataset.stock;
    const stockCode = stock.stockCode || stock.code;
    wx.navigateTo({
      url: `/pages/stock/index?code=${stockCode}`
    });
  },



  // 跳转到登录页面
  goToLogin: function () {
    wx.navigateTo({
      url: '/pages/login/index'
    });
  },

  // 下拉刷新
  onPullDownRefresh: function () {
    this.loadAllData().then(() => {
      wx.stopPullDownRefresh();
      wx.showToast({
        title: '刷新成功',
        icon: 'success'
      });
    });
  }
});